<template>
  <el-dialog :visible.sync="visible" :title="$t('oss.upload')" :close-on-click-modal="false" :close-on-press-escape="false">
    <el-upload
      :action="url"
      :file-list="fileList"
      drag
      multiple
	   :headers="token"
      :before-upload="beforeUploadHandle"
      :on-success="successHandle"
      class="text-center">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text" v-html="$t('upload.text')"></div>
      <div class="el-upload__tip" slot="tip">{{ $t('upload.tip', { 'format': okFileType }) }}</div>
    </el-upload>
  </el-dialog>
</template>

<script>
import Cookies from 'js-cookie'
import { setMd5 } from '@/utils'
export default {
  data () {
    return {
      visible: false,
      url: `${window.SITE_CONFIG['apiURL']}/common/upload/uploadFile`,
      num: 0,
      fileList: [],
	  token: {
	  	token: ''
	  }
    }
  },
  props:{
  	  upUrl:{
  		  type: String,
  		  default: `/common/upload/uploadFile`
  	  },
	  okFileType:{
		  type: String,
		  default: 'jpg、png、gif'
	  }
  },
  methods: {
    init () {
      this.visible = true
      this.num = 0
	  this.url = `${window.SITE_CONFIG['apiURL']}` + this.upUrl
      this.fileList = []
	  
	  
	  this.token.token = Cookies.get('token')
	  
	  const type = 'common';
	  const time = new Date().valueOf();
	  const thisurl = this.url.replace(`${window.SITE_CONFIG['apiURL']}`,'');
	  const suger = 'FastBoot.RickSun.Sugar';
	  const jg = '-';
	  const sign = setMd5(type + jg + thisurl + jg + time + jg + suger);
	  const passToken = type + jg + time + jg + sign;
	  this.token.passToken = passToken;
    },
    // 上传之前
    beforeUploadHandle (file) {
      // if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
      //   this.$message.error(this.$t('upload.tip', { 'format': 'jpg、png、gif' }))
      //   return false
      // }
      this.num++
    },
    // 上传成功
    successHandle (res, file, fileList) {
      if (res.code !== 200) {
        return this.$message.error(res.msg)
      }
      this.fileList = fileList
      this.num--
      if (this.num === 0) {
        this.$message({
          message: this.$t('prompt.success'),
          type: 'success',
          duration: 500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList',res.data)
          }
        })
      }
    }
  }
}
</script>
